//验证码
/**
 * idcode1 1.0 - validate user.
 * Version 1.0
 * @requires jQuery v1.2
 * author ehong[idehong@gmail.com]
 **/

/**
 * @example: $.idcode1.setCode();	
 * @desc: Make a validate code append to the element that id is idcode1.
 *
 * @example $.idcode1.validateCode();	
 * @desc return true if user input value equal idcode1. 
 **/

(function ($) {
    var settings = {
        e: 'idcode1',
        codeType: { name: 'follow', len: 4 },
        codeTip: 'refresh?',
        inputID: 'Txtidcode2'          //引用验证码输入框Id
    };

    var _set = {
        storeLable: 'codeval',
        store: '#ehong-code-input',
        codeval: '#ehong-code'
    }
    $.idcode1 = {
        getCode: function (option) {
            _commSetting(option);
            return _storeData(_set.storeLable, null);
        },
        setCode: function (option) {
            _commSetting(option);
            _setCodeStyle("#" + settings.e, settings.codeType.name, settings.codeType.len);

        },
        validateCode: function (option) {
            _commSetting(option);
            var inputV;
            if (settings.inputID) {
                inputV = $('#' + settings.inputID).val();
            } else {
                inputV = $(_set.store).val();
            }

            if (inputV.toLowerCase() == _storeData(_set.storeLable, null).toLowerCase()) {
                return true;
            } else {
                _setCodeStyle("#" + settings.e, settings.codeType.name, settings.codeType.len);
                return false;
            }
        }
    };

    function _commSetting(option) {
        $.extend(settings, option);
    }

    function _storeData(dataLabel, data) {
        var store = $(_set.codeval).get(0);
        if (data) {
            $.data(store, dataLabel, data);
        } else {
            return $.data(store, dataLabel);
        }
    }

    function _setCodeStyle(eid, codeType, codeLength) {
        var codeObj = _createCode(settings.codeType.name, settings.codeType.len);
        var randNum = Math.floor(Math.random() * 6);
        var htmlCode = ''
        if (!settings.inputID) {
            htmlCode = '<span><input id="ehong-code-input" type="text" maxlength="4" /></span>';
        }
        htmlCode += '<div id="ehong-code" class="ehong-idcode1-val ehong-idcode1-val';
        htmlCode += String(randNum);
        htmlCode += '" href="#" onblur="return false" onfocus="return false" oncontextmenu="return false" onclick="$.idcode1.setCode()">' + _setStyle(codeObj) + '</div>' + '<span id="ehong-code-tip-ck" class="ehong-code-val-tip" onclick="$.idcode1.setCode()">'/*+ settings.codeTip*/ + '</span>';
        $(eid).html(htmlCode);
        _storeData(_set.storeLable, codeObj);
    }

    function _setStyle(codeObj) {
        var fnCodeObj = new Array();
        var col = new Array('#BF0C43', '#E69A2A', '#707F02', '#18975F', '#BC3087', '#73C841', '#780320', '#90719B', '#1F72D8', '#D6A03C', '#6B486E', '#243F5F', '#16BDB5');
        var charIndex;
        for (var i = 0; i < codeObj.length; i++) {
            charIndex = Math.floor(Math.random() * col.length);
            fnCodeObj.push('<font color="' + col[charIndex] + '">' + codeObj.charAt(i) + '</font>');
        }
        return fnCodeObj.join('');
    }
    function _createCode(codeType, codeLength) {
        var codeObj;
        if (codeType == 'follow') {
            codeObj = _createCodeFollow(codeLength);
        } else if (codeType == 'calc') {
            codeObj = _createCodeCalc(codeLength);
        } else {
            codeObj = "";
        }
        return codeObj;
    }

    function _createCodeCalc(codeLength) {
        var code1, code2, codeResult;
        var selectChar = new Array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9');
        var charIndex;
        for (var i = 0; i < codeLength; i++) {
            charIndex = Math.floor(Math.random() * selectChar.length);
            code1 += selectChar[charIndex];

            charIndex = Math.floor(Math.random() * selectChar.length);
            code2 += selectChar[charIndex];
        }
        return [parseInt(code1), parseInt(code2), parseInt(code1) + parseInt(code2)];
    }

    function _createCodeFollow(codeLength) {
        var code = "";
        var selectChar = new Array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z');

        for (var i = 0; i < codeLength; i++) {
            var charIndex = Math.floor(Math.random() * selectChar.length);
            if (charIndex % 2 == 0) {
                code += selectChar[charIndex].toLowerCase();
            } else {
                code += selectChar[charIndex];
            }
        }
        return code;
    }

})(jQuery);



//login页面
$(function () {
    $("a").attr("href", "javascript:void(0)")
    //登录或手机切换
    $(".loginTit").on("click", "li", function () {
        $(this).children("a").addClass("current1").parents("li").siblings().children("a").removeClass("current1")
        $(".logForm").children().eq($(this).index()).show().siblings().hide()
        if ($(this).index() == 0) {
            $.idcode.validateCode()
        } else {
            $.idcode1.validateCode()
        }
    })


    $(window).load(function () {
        //登录效验
        $.idcode.setCode();//加载生成验证码方法
        $.idcode1.setCode();//加载生成验证码方法
        $.idcode.validateCode()
        render()
    })


    function render() {
        //用户名密码渲染到页面上去
        var clientCookie = JSON.parse($.cookie("client") || '[]')
        console.log(clientCookie)
        if (clientCookie.length == 0) {
            return
        }
        $("form").eq(0).find('[name="uname"]').val(clientCookie[clientCookie.length - 1].uname)
        $("form").eq(0).find('[name="upwd"]').val(clientCookie[clientCookie.length - 1].upwd)
    }



    //添加正则规则
    $.validator.addMethod("checkUname", function (val, el, flag) {
        return /^[a-z]\w{5,15}$/i.test(val)
    })

    //form表单1
    $("form").eq(0).validate({
        //规则
        rules: {
            uname: {
                required: true,//开启必填项
            },
            upwd: {
                required: true,
            }
        },
        //提示消息
        messages: {
            uname: {
                required: "用户名必填",
            },
            upwd: {
                required: "密码必填",
            }

        },
        //提交
        submitHandler: function () {
            remem()

            // if ($('[name="uname"]').val()) {
            //账号密码效验
            var isBy = $.idcode.validateCode()//验证码一致吗
            if (!isBy) {
                $(".yzmCheck").show()
                return false//阻止默认行为
            } else {
                $(".yzmCheck").hide()
                //把数据发到后台
                $.ajax({
                    url: "http://127.0.0.1:8080/api/login",
                    type: "post",
                    data: $("form").serialize(),//拿到form表单数据
                    dataType: "json",
                    beforeSend: function () {
                        layer.msg("正在登录...")
                    },
                    complete: function () {
                        layer.close()
                    }
                }).then(function (res) {
                    console.log(res.data)
                    if (res.status == 1) {
                        //将数据保存到
                        $.cookie("isLogin", JSON.stringify(res.data), {
                            expires: 10
                        })
                        //显示是否跳转到主页去的询问框
                        layer.confirm("登陆成功,是否跳转到主页?", {
                            btn: ["yes", "no"]
                        }, function (index) {
                            //yes
                            layer.close(index)
                            window.location.href = "http://127.0.0.1:8080/main.html"
                        }, function () {
                            //NO
                        })
                    } else {
                        layer.confirm("登录失败!")
                    }
                })
            }
            return false//阻止默认行为
        }
    })

    //form表单2
    $("form").eq(1).validate({
        //规则
        rules: {
            uphone: {
                required: true,//开启必填项
            },
        },
        //提示消息
        messages: {
            uphone: {
                required: "手机号必填",
            },
        },
        //提交
        submitHandler: function () {
            //手机号效验
            var isBy2 = $.idcode1.validateCode()//验证码一致吗
            console.log(isBy2)
            if (!isBy2) {
                console.log(isBy2)
                $(".yzmCheck").show()
                return false//阻止默认行为
            } else {
                $(".yzmCheck").hide()
                //把数据发到后台
                $.ajax({
                    url: "http://127.0.0.1:8080/api/login",
                    type: "post",
                    data: $("form").serialize(),//拿到form表单数据
                    dataType: "json",
                    beforeSend: function () {
                        layer.msg("正在登录...")
                    },
                    complete: function () {
                        layer.close()
                    }
                }).then(function (res) {
                    console.log(res.data)
                    if (res.status == 1) {
                        //将数据保存到
                        $.cookie("isLogin", JSON.stringify(res.data), {
                            expires: 1
                        })
                        //显示是否跳转到主页去的询问框
                        layer.confirm("登陆成功,是否跳转到主页?", {
                            btn: ["yes", "no"]
                        }, function (index) {
                            //yes
                            layer.close(index)
                            window.location.href = "http://127.0.0.1:8080/main.html"
                        }, function () {
                            //NO
                        })
                    } else {
                        layer.confirm("登录失败!")
                    }
                })
            }
            return false//阻止默认行为
        }
    })

    //如果点击记住密码,将密码保存到COOKIE中,打开界面时显示

    function remem() {
        if ($(".remPwd input").prop("checked")) {
            var cookieList = JSON.parse($.cookie("client") || '[]')
            var prams = {
                uname: $("form").eq(0).find('[name="uname"]').val(),
                upwd: $("form").eq(0).find('[name="upwd"]').val(),
                uphone: $("form").eq(1).find('[name="uphone"]').val()
            };
            cookieList.push(prams)
            $.cookie("client", JSON.stringify(cookieList), {
                expires: 3
            })
        }
    }
  

 


})



